<%@page import="com.bionic.banking.logic.DomainUtil"%>
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@page import="com.bionic.banking.core.entity.*"%>
<%@page import="com.bionic.banking.logic.controller.*" %>
<%@page import="java.util.Locale" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<%@taglib uri="../WEB-INF/taglib.tld" prefix="m" %> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Edit customer</title>
        <link type="text/css" href="../resources/css/demos.css" rel="stylesheet" />          
        <link rel="stylesheet" type="text/css" href="../resources/themes/smoothness/ui.all.css" />
        <link rel="stylesheet" href="../resources/themes/cupertino/jquery-ui.css" />          
        <script type="text/javascript" src="../resources/script/jquery.min.js"></script>
        <script type="text/javascript" src="../resources/script/ui/jquery-ui.min.js">
        </script>  
        <script type="text/javascript">                   
            $(function()
            {
                //1. Create the tabs
                $("#tabs").tabs();		
                                                 
                //2. Load image from file to JSP <img> tag
                $(":file").change(function(){                    
                    var file = this.files.item(0);
                    var url =  window.URL || window.webkitURL || window.mozURL || window.msURL;             
                    var blobURLref = url.createObjectURL(file,{autoRevoke:false});   
                    
                    //set blobURLref to display image
                    var img = $('#portret');
                    //img.onload=function(e) { alert(e.response.previewUrl()); }; 
                    img.attr("src", blobURLref);//var servletPath = "../ImageServlet?photoFile="+path;
                     
                    //get arraybuffer to be stored to dtabase
                    var xhr = new XMLHttpRequest();
                    xhr.open('GET', blobURLref, true);
                    xhr.responseType = 'arraybuffer';                    
                    xhr.onload = function(e) {           
                      //set image buffer (to be saved to DB)
                      var buffString = bufferToString(this.response);                    
                      $('#imageBuffer').val(buffString); 
                    };
                    xhr.send();                    
                });
                
                //3. Validation
                $('input[type="number"]').keyup(function(e)
                {
                    if (/\D/g.test(this.value))
                        this.value = this.value.replace(/\D/g, ''); // Filter non-digits from input value.
                });                     
                        
                $("[required=true]").after("<span></span>");
                
                $("[name=rbGender]").click(function()
                {
                    var genderName = this.val();                    
                    $("#gender").val(genderName == 'f' ? <%= Boolean.TRUE%> : <%= Boolean.FALSE%>);
                });
                    
                $("#btnSubmit").click(function()
                {       
                    var error=false;
                    $("span").text("");//Clear all error message
                                
                    $("[class~=Red]").removeClass("Red");
                    if(trim($("#firstName").val())==""){
                        $("#firstName").next().text(" Please enter a name");
                        $("#firstName").addClass("Red");
                        error=true;
                    }
                    if(trim($("#email").val())==""){
                        $("#email").next().text(" Please enter email");
                        $("#email").addClass("Red");
                        error=true;
                    }else if(!isEmail($("#email").val())){
                        $("#email").next().text(" Please enter valid Email");
                        $("#email").addClass("Red");
                        error=true;
                    }
                    if(trim($("#password").val())==""){
                        $("#password").next().text(" Please enter password");
                        $("#password").addClass("Red");
                        error=true;
                    }
                    else if($("#password").val()!=$("#c_password").val()){
                        $("#c_password").addClass("Red");
                        $("#c_password").parent().append("<span> Please verify password</span>");
                        error=true;
                    }
                              
                    if($("[name=rbGender]:checked").size()==0){                                      
                        $("#gender").addClass("Red");
                        $("#gender").parent().append("<span> Please select Gender</span>");
                        error=true;
                    }
                    
                    //red error style
                    $("[class=Red]").eq(0).focus();
                    return !error;
                });
            });     
            
            function bufferToString( buf ) {
                var view = new Uint8Array( buf );
                return Array.prototype.join.call(view, ",");
            }
            
            function trim(x) {
                return x.replace(/^\s+|$\s+/,'');
            }
            function isEmail(str)
            {
                var regex = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
                return regex.test(str);
            }
        </script>
    </head>
    <body>
        <form id="updateCustomerForm" method="post" action="../customer/Update.jsp">         
         <%
            Integer id= Integer.valueOf(request.getParameter("id"));        
            try 
            {
                CustomerController bean = new CustomerController();
                Customer customer = bean.getDetails(id);   
                
                UserController userBean = new UserController();
                User user = userBean.getDetails(customer.getUserId());
                
                AddressController addressBean = new AddressController();
                Address address = addressBean.getDetails(customer.getAddressId());
        %>
            <div id="tabs">
                <ul>
                    <li><a href="#divCustomer">Personal info</a></li>
                    <li><a href="#divAddress">Address</a></li>                 
                </ul>
               
                <jsp:useBean id="domainHelperBean" class="com.bionic.banking.logic.DomainUtil" />                 
                <div id="divCustomer" >
                    <table id="tblCustomer">      
                        <tr>
                            <td>Login</td>
                            <td>
                                <input id="login" name="login" type="text" required="true"
                                       value="<%= user.getLogin() %>" />
                            </td>
                            <td>Email</td>
                            <td><input id = "email" name="email" value="<%= customer.getEmail() %>" /></td>
                        </tr>
                        <tr>
                            <td>Password</td>
                            <td><input id="password" name="password" type="password" 
                                       value="<%= user.getPassword() %>" /></td>
                            <td>Password (verify):</td>
                            <td><input id="c_password" name="c_password" type="password"
                                       value="<%= user.getPassword() %>" /></td>
                        </tr>
                        <tr><td colspan="4" ><hr/></td></tr>
                        <tr>
                            <td>First Name</td>
                            <td><input id="id" name="id" value="<%= customer.getCustomerId() %>" 
                                       type="hidden"/>
                                <input required="true" type="text" value="<%= customer.getFirstName() %>"
                                       id = "firstName" name="firstName" />
                            </td>
                            <td>
                                Photo file
                                <input type="hidden" id = "imageBuffer" name="imageBuffer" />       
                            </td>
                            <td>                                
                               <input type="file" id = "photoFilePath" name="photoFilePath" />              
                            </td>  
                        </tr>
                        <tr>
                            <td>Last Name</td>
                            <td>
                                <input required="true" type="text" value="<%= customer.getLastName() %>"
                                       id = "lastName" name="lastName" />
                            </td>                                                        
                            <td rowspan="4">       
                               <img id="portret" name="portret" 
                                    src="../ImageServlet?customerId=${param.id}" width="100" height="100" />  
                            </td>
                        </tr>
                        <tr>
                            <td>Middle Name</td>
                            <td>
                                <input  type="text" value="<%= customer.getMiddleName() %>" 
                                        id = "middleName" name="middleName" >
                            </td>                                                  
                        </tr>
                        <tr>
                            <td>Age</td>                  
                            <td width="50">
                                <input value="<%= customer.getAge() %>" 
                                       id = "age" name="age" 
                                       <m:maskedInput mask="^[0-9]{1,2}$"/>/>
                            </td>
                        </tr>
                        <tr><td>Gender</td>
                            <c:set var="currGender" value="<%= customer.getGender() %>" />
                            <td>        
                                <input id="gender" name="gender" type="hidden" value="" />
                                <div id="divGender" class="floatLeft">
                                    <input id="rbMale" name="rbGender" type="radio" value="m"
                                    <c:if test="${!currGender}">checked="checked"</c:if> />
                                    <label for=rbMale>Male</label>
                                    <input id="rbFemale" name="rbGender" type="radio" value="f"
                                    <c:if test="${currGender}">checked="checked"</c:if> />
                                    <label for=rbFemale>Female</label>
                                </div>
                            </td></tr>
                        <tr>
                            <td>Phone</td>
                            <td>
                                <input id = "phone" name="phone"  
                                       value="<%= customer.getPhone() %>" />
                            </td>
                            <td>Fax</td>
                            <td><input id = "fax" name="fax" value="<%= customer.getFax() %>"/>
                            </td>
                        </tr>         
                    </table>
              </div>
   
              <div id="divAddress">                      
                 <table id="tblAddress">              
                     <tr><td>Country</td>
                         <td>
                          <c:set var="currCountry" value="<%= address.getCountry() %>" />
                              <select id="country" name="country">  
                                <c:forEach var="item" 
                                           items="${domainHelperBean.getCountries()}" >
                                    <option id="countryOption" value="${item.getCode()}" 
                                       <c:if test="${currCountry == item.getCode()}">
                                           selected="selected"</c:if>>
                                            ${item} 
                                    </option>
                                </c:forEach>
                              </select>                           
                        </td>
                        </tr>       
                        <tr>
                            <td>Region</td>
                            <td><input type="text" id = "region" name="region" 
                                       value="<%= address.getRegion() %>" /> </td>
                        </tr>
                       <tr>
                            <td>Postal Code</td>
                            <td><input id = "postalcode" name="postalcode" 
                                       value="<%= address.getPostalCode() %>" /></td>
                        </tr>
                        <tr>
                            <td>City</td>
                            <td><input id = "city" name="city" 
                                       value="<%= address.getCity() %>" /> </td>
                        </tr>
                        <tr>
                            <td>Street</td>
                            <td><input id = "street" name="street" 
                                       value="<%= address.getStreet() %>"/></td>
                        </tr>
                        <tr>
                            <td>Line1</td>
                            <td><input id = "line1" name="line1" 
                                       value="<%= address.getLine1() %>"/></td>
                        </tr>
                        <tr>
                            <td>Line2</td>
                            <td><input id = "line2" name="line2" 
                                       value="<%= address.getLine2() %>" /></td>
                        </tr>
                    </table>
                </div>        
            </div>
        <%   
            }
            catch(Exception e)
            {
                System.out.println(e);//TODO: logger
                //alert("error to update customer " + e);
            }
        %>
        <br/>
        <input type="submit" id="btnSubmit" value="Save" />     
        <a href="Controller?command=viewCustomersList"><strong>Go to List</strong></a>            
    </form>
 </body>